package com.isoftstone.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.isoftstone.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class FileController {
    @Value("${file.upload.path}")
    private String fileUploadPath;
    @Value("${file.upload.fileMapper}")
    private String fileMapper;
    @PostMapping("/upload")
    public Result<?> uploadFile(MultipartFile file) throws IOException{
        String fileName = file.getOriginalFilename();
        String fileType = FileUtil.extName(fileName);
        long fileSize = file.getSize();
        File uploadParentFile = new File(fileUploadPath);
        if(!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
//        重新命名名字
        String uuid=IdUtil.fastSimpleUUID();
        String newFileName = uuid+ StrUtil.DOT +fileType;
        String url = fileMapper+newFileName;
        File newFile = new File(fileUploadPath+newFileName);
//        将文件保存到指定目录
        file.transferTo(newFile);
        return Result.success(url);


    }

}
